<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Gemini AI 助手 - 内置风格</title>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            border-radius: 16px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5rem;
            margin-bottom: 10px;
        }

        .header p {
            opacity: 0.9;
            font-size: 1.1rem;
        }

        .form-container {
            padding: 40px;
        }

        .form-group {
            margin-bottom: 25px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            font-weight: 600;
            color: #374151;
        }

        input[type="url"],
        input[type="text"],
        select,
        textarea {
            width: 100%;
            padding: 12px 16px;
            border: 2px solid #e5e7eb;
            border-radius: 8px;
            font-size: 16px;
            transition: border-color 0.3s ease;
        }

        input[type="url"]:focus,
        input[type="text"]:focus,
        select:focus,
        textarea:focus {
            outline: none;
            border-color: #4f46e5;
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        textarea {
            resize: vertical;
            min-height: 100px;
            padding-right: 80px;
            
        }

        .submit-btn {
            width: 100%;
            background: linear-gradient(135deg, #4f46e5, #7c3aed);
            color: white;
            border: none;
            padding: 16px;
            border-radius: 8px;
            font-size: 18px;
            font-weight: 600;
            cursor: pointer;
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .submit-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(79, 70, 229, 0.3);
        }

        .submit-btn:disabled {
            background: #9ca3af;
            cursor: not-allowed;
            transform: none;
            box-shadow: none;
        }

        .loading {
            display: none;
            text-align: center;
            padding: 20px;
        }

        .spinner {
            border: 4px solid #f3f4f6;
            border-top: 4px solid #4f46e5;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 10px;
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }

            100% {
                transform: rotate(360deg);
            }
        }
        
        /* 彩虹文字动画 */
        .rainbow-model-name {
            font-size: 14px;
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .rainbow-text {
            font-weight: 600;
            background-image: linear-gradient(
                90deg,
                #ff0000, #ff9a00, #d0de21, #4fdc4a, #3fdad8, #2fc9e2, #1c7fee, #5f15f2, #ba0cf8, #fb07d9, #ff0000
            );
            background-size: 200% auto;
            color: transparent;
            -webkit-background-clip: text;
            background-clip: text;
            animation: rainbow-animation 5s linear infinite;
            display: inline-block;
            text-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
        }
        
        @keyframes rainbow-animation {
            to {
                background-position: 200% center;
            }
        }
        
        /* 风格选择器样式 */
        .style-selector {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 15px;
            margin-bottom: 20px;
        }
        
        .style-option {
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 15px;
            cursor: pointer;
            transition: all 0.3s ease;
            background: #f9fafb;
        }
        
        .style-option:hover {
            border-color: #4f46e5;
            background: #f8fafc;
        }
        
        .style-option.selected {
            border-color: #4f46e5;
            background: linear-gradient(135deg, rgba(79, 70, 229, 0.1), rgba(124, 58, 237, 0.1));
        }
        
        .style-title {
            font-weight: 600;
            color: #374151;
            margin-bottom: 8px;
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .style-description {
            font-size: 14px;
            color: #6b7280;
            line-height: 1.4;
        }
        
        .style-icon {
            font-size: 20px;
        }
        
        /* 图片选择交互优化 */
        .images-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }
        
        .image-item {
            position: relative;
            cursor: grab;
            transition: all 0.2s ease;
            border-radius: 8px;
            overflow: hidden;
        }
        
        .image-item:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        
        .image-item.dragging {
            opacity: 0.7;
            box-shadow: 0 10px 20px rgba(0,0,0,0.2);
            cursor: grabbing;
        }
        
        .image-preview-wrapper {
            position: relative;
            aspect-ratio: 1 / 1;
            border-radius: 8px;
            overflow: hidden;
            background: #f3f4f6;
            pointer-events: none; /* 允许拖拽事件穿透 */
        }
        
        .preview-thumbnail {
            width: 100%;
            height: 100%;
            object-fit: cover;
            transition: transform 0.3s ease;
            pointer-events: none; /* 允许拖拽事件穿透 */
        }
        
        .image-item:hover .preview-thumbnail {
            transform: scale(1.05);
        }
        
        .image-number {
            position: absolute;
            top: 8px;
            left: 8px;
            width: 24px;
            height: 24px;
            background: rgba(0, 0, 0, 0.5);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            z-index: 2;
        }
        
        .remove-image-btn {
            position: absolute;
            top: 8px;
            right: 8px;
            width: 24px;
            height: 24px;
            border: none;
            background: rgba(239, 68, 68, 0.9);
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            cursor: pointer;
            z-index: 2;
            opacity: 0;
            transition: opacity 0.2s ease;
            pointer-events: auto; /* 删除按钮需要响应点击 */
        }
        
        .image-item:hover .remove-image-btn {
            opacity: 1;
        }
        
        .image-info-overlay {
            padding: 8px;
            background: #f9fafb;
            display: flex;
            align-items: center;
            gap: 5px;
            border-top: 1px solid #e5e7eb;
            pointer-events: none; /* 允许拖拽事件穿透 */
        }
        
        .type-icon {
            font-size: 12px;
        }
        
        .image-short-info {
            font-size: 12px;
            color: #6b7280;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
        
        .image-counter {
            color: #4b5563;
            font-size: 14px;
            font-weight: 600;
            margin-bottom: 10px;
        }
        
        .drag-hint {
            color: #6b7280;
            font-size: 12px;
            margin-bottom: 10px;
            background: #f3f4f6;
            padding: 6px 10px;
            border-radius: 4px;
            display: inline-block;
        }
        
        /* 整个页面拖拽效果 */
        .dragover-body {
            position: relative;
        }
        
        .dragover-body::before {
            content: '📁 拖拽图片文件到此处上传';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(59, 130, 246, 0.1);
            backdrop-filter: blur(2px);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            font-weight: bold;
            color: #2563eb;
            z-index: 9999;
            border: 3px dashed #2563eb;
            box-sizing: border-box;
        }
        
        .floating-success {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            background: rgba(16, 185, 129, 0.9);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            font-size: 14px;
            z-index: 1000;
            animation: fadeInOut 2s ease forwards;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        @keyframes fadeInOut {
            0% { opacity: 0; transform: translate(-50%, 20px); }
            15% { opacity: 1; transform: translate(-50%, 0); }
            85% { opacity: 1; transform: translate(-50%, 0); }
            100% { opacity: 0; transform: translate(-50%, -20px); }
        }
        
        .upload-area.minimized {
            padding: 10px;
            transition: all 0.3s ease;
        }
        
        .upload-area.minimized p {
            display: none;
        }
        
        .upload-area {
            transition: all 0.3s ease;
        }

        .result {
            display: none;
            margin-top: 30px;
            padding: 20px;
            background: #f9fafb;
            border-radius: 8px;
        }

        .result h3 {
            margin-bottom: 15px;
            color: #374151;
        }

        .image-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 15px;
        }

        .result-image {
            width: 100%;
            border-radius: 8px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }

        .result-image-container {
            position: relative;
            display: flex;
            flex-direction: column;
            align-items: center;
        }

        .result-image-buttons {
            display: flex;
            gap: 8px;
            margin-top: 10px;
            opacity: 1;
        }

        .reuse-btn,
        .download-btn {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            font-weight: 500;
            transition: all 0.3s ease;
        }

        .reuse-btn {
            background: #4f46e5;
            color: white;
        }

        .reuse-btn:hover {
            background: #4338ca;
            transform: translateY(-1px);
        }

        .download-btn {
            background: #059669;
            color: white;
        }

        .download-btn:hover {
            background: #047857;
            transform: translateY(-1px);
        }

        .error {
            display: none;
            background: #fef2f2;
            border: 1px solid #fecaca;
            color: #dc2626;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
        }

        .image-input-section {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 20px;
            text-align: center;
            transition: border-color 0.3s ease;
            margin-bottom: 25px;
        }

        .image-input-section.dragover {
            border-color: #4f46e5;
            background-color: #f8fafc;
        }

        .image-input-section.paste-ready {
            border-color: #059669;
            background-color: #f0fdf4;
            animation: pulse 2s infinite;
        }

        @keyframes pulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: 0.8;
            }
        }

        .upload-area {
            margin-bottom: 15px;
        }

        .upload-btn {
            background: #4f46e5;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin-right: 10px;
            transition: background-color 0.3s ease;
        }

        .upload-btn:hover {
            background: #4338ca;
        }

        .file-input {
            display: none;
        }

        .url-input-container {
            display: flex;
            gap: 10px;
            align-items: center;
            margin-top: 15px;
        }

        .url-input {
            flex: 1;
        }

        .preview-btn {
            background: #059669;
            color: white;
            border: none;
            padding: 12px 20px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 14px;
            white-space: nowrap;
        }

        .preview-btn:hover {
            background: #047857;
        }

        .image-preview {
            display: none;
            margin-top: 20px;
            text-align: center;
        }

        .preview-image {
            max-width: 100%;
            max-height: 300px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .preview-info {
            margin-top: 10px;
            color: #6b7280;
            font-size: 14px;
        }

        .clear-image {
            background: #dc2626;
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            margin-top: 10px;
        }

        .clear-image:hover {
            background: #b91c1c;
        }

        .row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
        }

        .prompt-row {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 20px;
            margin-bottom: 25px;
        }

        .prompt-left,
        .prompt-right {
            margin-bottom: 0;
        }

        @media (max-width: 768px) {
            .row {
                grid-template-columns: 1fr;
            }

            .prompt-row {
                grid-template-columns: 1fr;
                gap: 15px;
            }

            .header h1 {
                font-size: 2rem;
            }

            .form-container {
                padding: 20px;
            }

            .url-input-container {
                flex-direction: column;
            }

            .preview-btn {
                width: 100%;
            }

            .style-selector {
                grid-template-columns: 1fr;
            }

            textarea {
                padding-right: 16px;
                /* 移动端恢复正常内边距 */
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="header">
            <h1>🎨 Gemini AI 助手 - 内置风格</h1>
            <p>使用预设风格快速生成专业级图片</p>
        </div>

        <div class="form-container">
            <form id="imageEditForm">
                <div class="form-group">
                    <label>选择图片 (支持多张，可选)</label>
                    <div class="image-input-section" id="imageInputSection">
                        <div class="upload-area">
                            <p style="margin-bottom: 15px; color: #6b7280;">
                                拖拽图片到此处、点击上传或按 Ctrl+V 粘贴剪贴板图片
                            </p>
                            <div style="display: flex; gap: 10px; justify-content: center; flex-wrap: wrap;">
                                <button type="button" class="upload-btn"
                                    onclick="document.getElementById('fileInput').click()">
                                    📁 选择文件
                                </button>
                                <button type="button" class="upload-btn" onclick="pasteFromClipboard()">
                                    📋 粘贴图片
                                </button>
                            </div>
                            <input type="file" id="fileInput" class="file-input" accept="image/*" multiple>
                        </div>

                        <div style="margin: 15px 0; color: #9ca3af;">或者</div>

                        <div class="url-input-container">
                            <input type="url" id="imageUrl" class="url-input"
                                placeholder="输入图片 URL: https://example.com/image.jpg">
                            <button type="button" class="preview-btn" id="addUrlBtn">➕ 添加</button>
                        </div>
                    </div>

                    <div class="image-preview" id="imagePreview">
                        <img id="previewImage" class="preview-image" alt="图片预览">
                        <div class="preview-info" id="previewInfo"></div>
                        <button type="button" class="clear-image" id="clearImage">清除图片</button>
                    </div>
                </div>

                <div class="form-group">
                    <label>选择风格</label>
                    <div class="style-selector">
                        <div class="style-option" data-style="skyline">
                            <div class="style-title">
                                <span class="style-icon">🏙️</span>
                                天际线风格
                            </div>
                            <div class="style-description">
                                将建筑照片转换为《城市：天际线》游戏风格的3D建筑模型，具有逼真的光影效果和材质细节
                            </div>
                        </div>
                        <div class="style-option" data-style="bandai">
                            <div class="style-title">
                                <span class="style-icon">🎎</span>
                                Bandai 手办风格
                            </div>
                            <div class="style-description">
                                将照片转换为1/7比例的商业手办，包含透明包装盒和圆形底座，呈现真实的PVC材质效果
                            </div>
                        </div>
                        <div class="style-option" data-style="portrait">
                            <div class="style-title">
                                <span class="style-icon">📸</span>
                                黑白肖像风格
                            </div>
                            <div class="style-description">
                                将人物照片转换为摄影棚拍摄的高分辨率黑白肖像艺术作品
                            </div>
                        </div>
                        <div class="style-option" data-style="film_simulation">
                            <div class="style-title">
                                <span class="style-icon">🎞️</span>
                                胶片模拟风格
                            </div>
                            <div class="style-description">
                                将人物照片转换为摄影棚拍摄的高分辨率彩色肖像艺术作品，模仿柯达波特拉胶卷风格
                            </div>
                        </div>
                        <div class="style-option" data-style="polaroid_instant">
                            <div class="style-title">
                                <span class="style-icon">📸</span>
                                宝丽来即时成像风格
                            </div>
                            <div class="style-description">
                                将人物照片转换为摄影棚拍摄的高分辨率彩色肖像艺术作品，模仿宝丽来即时成像相纸的复古艺术风格
                            </div>
                        </div>
                        <div class="style-option" data-style="disposable_camera_90s">
                            <div class="style-title">
                                <span class="style-icon">📸</span>
                                90年代一次性相机直闪风格
                            </div>
                            <div class="style-description">
                                将人物照片转换为摄影棚拍摄的高分辨率彩色肖像艺术作品，模仿90年代一次性胶片傻瓜相机的直闪美学
                            </div>
                        </div>
                        <div class="style-option" data-style="black_soft_focus">
                            <div class="style-title">
                                <span class="style-icon">📸</span>
                                黑柔焦滤镜风格
                            </div>
                            <div class="style-description">
                                将人物照片转换为摄影棚拍摄的高分辨率黑白肖像艺术作品，带有明显的黑柔焦滤镜电影感
                            </div>
                        </div>
                        <div class="style-option" data-style="cinematic_color_grading">
                            <div class="style-title">
                                <span class="style-icon">🎬</span>
                                电影感调色风格
                            </div>
                            <div class="style-description">
                                将人物照片转换为摄影棚拍摄的高分辨率电影感彩色肖像艺术作品
                            </div>
                        </div>
                        <div class="style-option selected" data-style="custom">
                            <div class="style-title">
                                <span class="style-icon">✨</span>
                                自定义风格
                            </div>
                            <div class="style-description">
                                使用自定义提示词，发挥创意进行个性化图片编辑或生成
                            </div>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="prompt">提示词 *</label>
                    <textarea id="prompt" name="prompt" required
                        placeholder="描述你想要对图片进行的编辑，例如：将背景改为蓝天白云，或者 Change the background to blue sky with white clouds"></textarea>
                </div>

                <div class="row">
                    <div class="form-group">
                        <div class="rainbow-model-name">
                            <strong>模型:</strong> <span class="rainbow-text">Gemini 2.5 Flash Image Preview</span>
                        </div>
                        <input type="hidden" name="modelType" value="gemini" />
                    </div>
                </div>

                <button type="submit" class="submit-btn" id="submitBtn">
                    开始处理
                </button>
            </form>

            <div class="loading" id="loading">
                <div class="spinner"></div>
                <p>正在处理中，请稍候...</p>
            </div>

            <div class="error" id="error"></div>

            <div class="result" id="result">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
                    <h3 style="margin: 0;">处理结果</h3>
                    <button type="button" class="clear-image" id="clearResultBtn" style="display: none;">🗑️ 清除结果</button>
                </div>
                <div class="image-grid" id="imageGrid"></div>
            </div>
        </div>
    </div>

    <script>
        // const API_KEY = 'sk-7vylVCM3AHsxeIOeCb11BfB235314eD1B0D9Fe21F888B1De';
        const API_KEY = 'sk-NNISovW1HS5UJbyRA36e5fF05aA9460a957dD8799725E96f';
        const BASE_URL = 'https://api.laozhang.ai/v1';

        let currentImages = [];
        let uploadedFiles = [];
        let selectedStyle = 'custom';

        // 预设风格的提示词
        const stylePrompts = {
            skyline: `Based on this architectural photograph, generate a high-fidelity 3D building model in the style of "Cities: Skylines." Key Requirements: Aim for a realistic look, preserving the main structure and texture details of the building, but stylized for a game. Emphasize realistic lighting and shadow effects. Use a 45-degree top-down perspective to showcase the building's three-dimensionality. Materials should be clearly defined, such as reflective glass and metallic surfaces. It should look like a high-quality 3D render suitable for a game engine.`,
            bandai: `Please turn this photo into a figure. Behind it, there should be a partially transparent plastic paper box with the character from this photo printed on it. In front of the box, on a round plastic base, place the figure version of the image I gave you. I want the PVC material to be clearly represented. It would be even better if the background were indoors. A 1/7 scale commercial figurine of the character in the picture was drawn, in a realistic style and in a real environment. The figurine was placed on a computer desk with a round transparent acrylic base with no text on it. The content on the computer screen was the brush modeling process of the figurine, and next to the computer screen was a BANDAI-style toy box with the original painting printed on it.`, 
            portrait: `将上图中的人物转换为一张摄影棚拍摄的高分辨率的黑白肖像艺术作品，要求半身照，动作协调自然，特写镜头，聚焦在面部。 人物的服装和动作改为都市休闲风格，整体氛围偏向深邃但不刻意。整体效果安静、深邃且温柔。背景呈现柔和渐变效果，营造出层次感与寂静氛围。细腻的胶片颗粒质感为画面增添了一种可触摸的、模拟摄影般的柔和质地，让人联想到经典的黑白摄影。 一束温柔的定向光，柔和地漫射开来，轻抚他的面颊曲线，或在眼中闪现光点——这是画面的情感核心。其余部分以大量负空间占据，刻意保持简洁，使画面自由呼吸。画面中没有文字、没有标志——只有光影与情绪交织。顶级摄影师的人物肖像照风格，非中心构图`,
            film_simulation: `将上图中的人物转换为一张摄影棚拍摄的高分辨率的彩色肖像艺术作品，模仿柯达波特拉胶卷（Kodak Portra）的独特风格。要求半身照，动作协调自然，特写镜头，聚焦在面部。人物的服装和动作改为都市休闲风格，整体氛围偏向深邃但不刻意。整体效果安静、深邃且温柔。背景呈现柔和渐变效果，营造出层次感与寂静氛围。细腻的胶片颗粒质感为画面增添了一种可触摸的、模拟摄影般的柔和质地，色彩温暖而饱和，人物肤色呈现出健康迷人的奶油色调。一束温柔的定向光，柔和地漫射开来，轻抚他的面颊曲线，或在眼中闪现光点——这是画面的情感核心`,
            polaroid_instant: `将上图转换为一张摄影棚拍摄的高分辨率的彩色肖像艺术作品，模仿宝丽来（Polaroid）即时成像相纸的复古艺术风格。要求半身照，动作协调自然，特写镜头，聚焦在面部。人物的服装和动作改为都市休闲风格，整体氛围偏向深邃且充满怀旧的亲密感。整体效果安静、深邃且温柔。背景呈现柔和渐变效果。整体色彩偏暖，饱和度略微降低，高光部分泛着一层柔和的奶油色调，而阴影则呈现出独特的、略带青色的化学感，取代了常规的胶片颗粒。一束温柔的定向光，柔和地漫射开来，轻抚他的面颊曲线，或在眼中闪现柔和的光点——这是画面的情感核心。其余部分以大量负空间占据。画面中没有文字、没有标志——只有独特的色彩与情绪交织。顶级摄影师的人物肖像照风格，非中心构图。`,
            disposable_camera_90s: `将上图中的人物转换为一张摄影棚拍摄的高分辨率的彩色肖像艺术作品，模仿90年代一次性胶片傻瓜相机的直闪美学。要求半身照，动作协调自然，特写镜头，聚焦在面部。人物的服装和动作改为都市休闲风格，整体氛围偏向深邃但充满原始的、不加修饰的真实感。背景呈现柔和渐变效果，但因闪光距离而自然变暗。画面颗粒感明显，色彩饱和但略有偏色。一束来自相机方向的、略显生硬的直射闪光，取代了柔和的定向光，在他脸上制造出明亮的中心高光和快速衰减的硬朗阴影——这是画面的视觉核心。其余部分以大量负空间占据，刻意保持简洁，使画面自由呼吸。画面中没有文字、没有标志——只有生猛的光线与瞬间的情绪交织。顶级摄影师的人物肖像照风格，非中心构图。`,
            black_soft_focus: `将上图中的人物转换为一张摄影棚拍摄的高分辨率的黑白肖像艺术作品，带有明显的黑柔焦滤镜电影感。要求半身照，动作协调自然，特写镜头，聚焦在面部。人物的服装和动作改为都市休闲风格，整体氛围偏向深邃但不刻意。整体效果安静、深邃且温柔。背景呈现柔和渐变效果，营造出层次感与寂静氛围。细腻的胶片颗粒质感为画面增添了一种可触摸的、模拟摄影般的柔和质地。一束温柔的定向光，柔和地漫射开来，在高光区域边缘形成一层细腻、梦幻的光晕，轻抚他的面颊曲线，或在眼中闪现柔和的光点——这是画面的情感核心。其余部分以大量负空间占据，刻意保持简洁，使画面自由呼吸。画面中没有文字、没有标志——只有光影与情绪交织。顶级摄影师的人物肖像照风格，非中心构图。`,
            cinematic_color_grading: `将上图中的人物转换为一张摄影棚拍摄的高分辨率的电影感彩色肖像艺术作品。要求半身照，动作协调自然，特写镜头，聚焦在面部。人物的服装和动作改为都市休闲风格，整体氛围偏向深邃但不刻意。整体效果安静、深邃且充满戏剧张力。背景呈现从深青色到蓝黑色的柔和渐变，营造出层次感与寂静氛围。细腻的胶片颗粒质感为画面增添了一种可触摸的、模拟摄影般的柔和质地。一束温暖的、偏橙色的定向光，柔和地漫射开来，轻抚他的面颊曲线，或在眼中闪现光点——这是画面的情感核心。其余部分以大量负空间占据，通过青橙互补色调强化了画面的叙事感。画面中没有文字、没有标志——只有光影与情绪交织。顶级摄影师的人物肖像照风格，非中心构图。`
        };

        // 初始化事件监听器
        document.addEventListener('DOMContentLoaded', function () {
            initializeEventListeners();
            initializeStyleSelector();
        });

        function initializeEventListeners() {
            // 文件上传
            document.getElementById('fileInput').addEventListener('change', handleFileUpload);

            // URL 预览
            document.getElementById('addUrlBtn').addEventListener('click', handleUrlPreview);

            // 清除图片
            document.getElementById('clearImage').addEventListener('click', clearImage);

            // 清除结果
            document.getElementById('clearResultBtn').addEventListener('click', clearResult);

            // 拖拽上传 - 支持整个页面拖拽
            document.body.addEventListener('dragover', handleDragOver);
            document.body.addEventListener('dragleave', handleDragLeave);
            document.body.addEventListener('drop', handleDrop);

            // 剪贴板粘贴支持
            document.addEventListener('paste', handlePaste);
            document.addEventListener('keydown', handleKeyDown);

            // 表单提交
            document.getElementById('imageEditForm').addEventListener('submit', handleFormSubmit);
        }

        function initializeStyleSelector() {
            const styleOptions = document.querySelectorAll('.style-option');
            const promptTextarea = document.getElementById('prompt');

            styleOptions.forEach(option => {
                option.addEventListener('click', function() {
                    // 移除所有选中状态
                    styleOptions.forEach(opt => opt.classList.remove('selected'));
                    // 添加选中状态
                    this.classList.add('selected');
                    
                    selectedStyle = this.dataset.style;
                    
                    // 根据选择的风格更新提示词
                    if (selectedStyle === 'custom') {
                        promptTextarea.placeholder = '描述你想要对图片进行的编辑，例如：将背景改为蓝天白云，或者 Change the background to blue sky with white clouds';
                        if (promptTextarea.value === stylePrompts.skyline || promptTextarea.value === stylePrompts.bandai) {
                            promptTextarea.value = '';
                        }
                    } else {
                        promptTextarea.value = stylePrompts[selectedStyle];
                        promptTextarea.placeholder = '已自动填入预设风格提示词，您可以根据需要进行修改';
                    }
                });
            });
        }

        async function handleFileUpload(e) {
            const files = e.target.files;
            for (let file of files) {
                await processFile(file);
            }
            updateImageDisplay();
        }

        async function processFile(file) {
            if (!file.type.startsWith('image/')) {
                showError('请选择有效的图片文件');
                return;
            }

            const reader = new FileReader();
            reader.onload = function (e) {
                const imageData = {
                    id: Date.now() + Math.random(),
                    type: 'file',
                    data: e.target.result,
                    name: file.name,
                    size: file.size
                };
                currentImages.push(imageData);
                uploadedFiles.push(file);
                updateImageDisplay();
                showFloatingMessage(`已添加图片: ${file.name}`);
            };
            reader.readAsDataURL(file);
        }

        async function handleUrlPreview() {
            const url = document.getElementById('imageUrl').value.trim();
            if (!url) {
                showError('请输入图片URL');
                return;
            }

            if (!isValidImageUrl(url)) {
                showError('请输入有效的图片URL');
                return;
            }

            try {
                // 检查图片是否可以加载
                const img = new Image();
                img.crossOrigin = 'anonymous';
                
                img.onload = function() {
                    const imageData = {
                        id: Date.now() + Math.random(),
                        type: 'url',
                        data: url,
                        name: url.split('/').pop() || 'image',
                        size: 'Unknown'
                    };
                    currentImages.push(imageData);
                    updateImageDisplay();
                    document.getElementById('imageUrl').value = '';
                    showFloatingMessage('已添加图片URL');
                };
                
                img.onerror = function() {
                    showError('无法加载该图片URL，请检查链接是否有效');
                };
                
                img.src = url;
            } catch (error) {
                showError('添加图片URL时出错: ' + error.message);
            }
        }

        function isValidImageUrl(url) {
            try {
                new URL(url);
                return /\.(jpg|jpeg|png|gif|bmp|webp)$/i.test(url);
            } catch {
                return false;
            }
        }

        function updateImageDisplay() {
            const imageInputSection = document.getElementById('imageInputSection');
            const uploadArea = imageInputSection.querySelector('.upload-area');
            
            // 移除现有的图片网格
            const existingGrid = imageInputSection.querySelector('.images-grid');
            if (existingGrid) {
                existingGrid.remove();
            }
            
            // 移除现有的计数器和提示
            const existingCounter = imageInputSection.querySelector('.image-counter');
            const existingHint = imageInputSection.querySelector('.drag-hint');
            if (existingCounter) existingCounter.remove();
            if (existingHint) existingHint.remove();
            
            if (currentImages.length > 0) {
                // 最小化上传区域
                uploadArea.classList.add('minimized');
                
                // 添加图片计数器
                const counter = document.createElement('div');
                counter.className = 'image-counter';
                counter.textContent = `已选择 ${currentImages.length} 张图片`;
                imageInputSection.appendChild(counter);
                
                // 添加拖拽提示
                const hint = document.createElement('div');
                hint.className = 'drag-hint';
                hint.textContent = '💡 拖拽图片可调整顺序';
                imageInputSection.appendChild(hint);
                
                // 创建图片网格
                const grid = document.createElement('div');
                grid.className = 'images-grid';
                
                currentImages.forEach((image, index) => {
                    const item = createImageItem(image, index);
                    grid.appendChild(item);
                });
                
                imageInputSection.appendChild(grid);
                
                // 初始化拖拽排序
                initializeDragSort(grid);
            } else {
                // 恢复上传区域
                uploadArea.classList.remove('minimized');
            }
        }

        function createImageItem(image, index) {
            const item = document.createElement('div');
            item.className = 'image-item';
            item.draggable = true;
            item.dataset.index = index;
            
            const wrapper = document.createElement('div');
            wrapper.className = 'image-preview-wrapper';
            
            const img = document.createElement('img');
            img.className = 'preview-thumbnail';
            img.src = image.data;
            img.alt = image.name;
            
            const number = document.createElement('div');
            number.className = 'image-number';
            number.textContent = index + 1;
            
            const removeBtn = document.createElement('button');
            removeBtn.className = 'remove-image-btn';
            removeBtn.innerHTML = '×';
            removeBtn.onclick = (e) => {
                e.stopPropagation();
                removeImage(image.id);
            };
            
            const overlay = document.createElement('div');
            overlay.className = 'image-info-overlay';
            
            const typeIcon = document.createElement('span');
            typeIcon.className = 'type-icon';
            typeIcon.textContent = image.type === 'file' ? '📁' : '🔗';
            
            const info = document.createElement('span');
            info.className = 'image-short-info';
            info.textContent = image.name;
            
            overlay.appendChild(typeIcon);
            overlay.appendChild(info);
            
            wrapper.appendChild(img);
            wrapper.appendChild(number);
            wrapper.appendChild(removeBtn);
            
            item.appendChild(wrapper);
            item.appendChild(overlay);
            
            return item;
        }

        function removeImage(imageId) {
            currentImages = currentImages.filter(img => img.id !== imageId);
            updateImageDisplay();
            showFloatingMessage('已移除图片');
        }

        function initializeDragSort(grid) {
            let draggedElement = null;
            
            grid.addEventListener('dragstart', (e) => {
                if (e.target.classList.contains('image-item')) {
                    draggedElement = e.target;
                    e.target.classList.add('dragging');
                }
            });
            
            grid.addEventListener('dragend', (e) => {
                if (e.target.classList.contains('image-item')) {
                    e.target.classList.remove('dragging');
                    draggedElement = null;
                }
            });
            
            grid.addEventListener('dragover', (e) => {
                e.preventDefault();
                const afterElement = getDragAfterElement(grid, e.clientY);
                if (afterElement == null) {
                    grid.appendChild(draggedElement);
                } else {
                    grid.insertBefore(draggedElement, afterElement);
                }
            });
            
            grid.addEventListener('drop', (e) => {
                e.preventDefault();
                // 重新排序数组
                const newOrder = Array.from(grid.children).map(item => {
                    const index = parseInt(item.dataset.index);
                    return currentImages[index];
                });
                currentImages = newOrder;
                updateImageDisplay();
            });
        }

        function getDragAfterElement(container, y) {
            const draggableElements = [...container.querySelectorAll('.image-item:not(.dragging)')];
            
            return draggableElements.reduce((closest, child) => {
                const box = child.getBoundingClientRect();
                const offset = y - box.top - box.height / 2;
                
                if (offset < 0 && offset > closest.offset) {
                    return { offset: offset, element: child };
                } else {
                    return closest;
                }
            }, { offset: Number.NEGATIVE_INFINITY }).element;
        }

        function clearImage() {
            currentImages = [];
            uploadedFiles = [];
            updateImageDisplay();
            document.getElementById('imageUrl').value = '';
            showFloatingMessage('已清除所有图片');
        }

        function clearResult() {
            const resultDiv = document.getElementById('result');
            const imageGrid = document.getElementById('imageGrid');
            const clearBtn = document.getElementById('clearResultBtn');
            
            imageGrid.innerHTML = '';
            resultDiv.style.display = 'none';
            clearBtn.style.display = 'none';
        }

        async function pasteFromClipboard() {
            try {
                const clipboardItems = await navigator.clipboard.read();
                
                for (const clipboardItem of clipboardItems) {
                    for (const type of clipboardItem.types) {
                        if (type.startsWith('image/')) {
                            const blob = await clipboardItem.getType(type);
                            const file = new File([blob], `clipboard-${Date.now()}.${type.split('/')[1]}`, { type });
                            await processFile(file);
                            showFloatingMessage('已从剪贴板添加图片');
                            return;
                        }
                    }
                }
                
                showError('剪贴板中没有找到图片');
            } catch (error) {
                showError('无法访问剪贴板: ' + error.message);
            }
        }

        // 拖拽上传处理
        function handleDragOver(e) {
            e.preventDefault();
            if (e.dataTransfer.types.includes('Files')) {
                document.body.classList.add('dragover-body');
            }
        }

        function handleDragLeave(e) {
            if (!e.relatedTarget || !document.body.contains(e.relatedTarget)) {
                document.body.classList.remove('dragover-body');
            }
        }

        async function handleDrop(e) {
            e.preventDefault();
            document.body.classList.remove('dragover-body');
            
            const files = Array.from(e.dataTransfer.files).filter(file => file.type.startsWith('image/'));
            
            if (files.length === 0) {
                showError('请拖拽图片文件');
                return;
            }
            
            for (const file of files) {
                await processFile(file);
            }
        }

        // 键盘快捷键处理
        function handleKeyDown(e) {
            if (e.ctrlKey && e.key === 'v') {
                e.preventDefault();
                pasteFromClipboard();
            }
        }

        // 剪贴板粘贴处理
        async function handlePaste(e) {
            const items = e.clipboardData?.items;
            if (!items) return;
            
            for (const item of items) {
                if (item.type.startsWith('image/')) {
                    e.preventDefault();
                    const file = item.getAsFile();
                    if (file) {
                        await processFile(file);
                        showFloatingMessage('已从剪贴板添加图片');
                    }
                    break;
                }
            }
        }

        async function handleFormSubmit(e) {
            e.preventDefault();
            
            const prompt = document.getElementById('prompt').value.trim();
            
            if (!prompt) {
                showError('请输入提示词');
                return;
            }
            
            showLoading('正在处理中，请稍候...');
            hideError();
            
            try {
                const imageData = currentImages.map(img => img.data);
                const result = await editImage(prompt, imageData);
                showResult(result);
            } catch (error) {
                console.error('处理失败:', error);
                showError('处理失败: ' + error.message);
            } finally {
                hideLoading();
            }
        }

        async function editImage(prompt, images) {
            return await editImageWithGemini(prompt, images);
        }

        async function editImageWithGemini(prompt, images) {
            // 在原有 prompt 基础上添加只返回 base64 URL 的要求
            const enhancedPrompt = prompt + "\n\n重要：请只返回生成图片的 base64 数据 URL（格式：data:image/png;base64,...），不要包含任何其他文字说明或描述。";
            
            const content = [
                {
                    type: "text",
                    text: enhancedPrompt
                }
            ];
            
            // 只有在有图片时才添加图片内容
            if (images && images.length > 0) {
                images.forEach(imageUrl => {
                    content.push({
                        type: "image_url",
                        image_url: {
                            url: imageUrl
                        }
                    });
                });
            }
            
            const response = await fetch(`${BASE_URL}/chat/completions`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${API_KEY}`
                },
                body: JSON.stringify({
                    model: "gemini-2.5-flash-image-preview",
                    messages: [
                        {
                            role: "user",
                            content: content
                        }
                    ],
                    max_tokens: 4000
                })
            });
            
            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error?.message || `HTTP ${response.status}`);
            }
            
            const data = await response.json();
            console.log('API Response:', data); // 调试日志
            return data.choices[0].message.content;
        }

        function showResult(content) {
            const resultDiv = document.getElementById('result');
            const imageGrid = document.getElementById('imageGrid');
            const clearBtn = document.getElementById('clearResultBtn');
            
            // 清空之前的结果
            imageGrid.innerHTML = '';
            
            // 检测是否包含图片数据
            const imageRegex = /!\[image\]\((data:image\/[^;]+;base64,[^)]+)\)/g;
            const base64Regex = /(data:image\/[^;]+;base64,[A-Za-z0-9+\/=]+)/g;
            
            let hasImages = false;
            let processedContent = content;
            
            // 处理 Markdown 格式的图片
            let match;
            while ((match = imageRegex.exec(content)) !== null) {
                hasImages = true;
                const imageDataUrl = match[1];
                
                // 创建图片容器
                const imageContainer = document.createElement('div');
                imageContainer.className = 'result-image-container';
                
                // 创建图片元素
                const img = document.createElement('img');
                img.src = imageDataUrl;
                img.className = 'result-image';
                img.style.cssText = `
                    max-width: 100%;
                    height: auto;
                    border-radius: 8px;
                    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                    margin-bottom: 10px;
                `;
                
                // 创建按钮容器
                const buttonContainer = document.createElement('div');
                buttonContainer.className = 'result-image-buttons';
                
                // 下载按钮
                const downloadBtn = document.createElement('button');
                downloadBtn.className = 'download-btn';
                downloadBtn.textContent = '💾 下载图片';
                downloadBtn.onclick = () => downloadImage(imageDataUrl, `generated-image-${Date.now()}.png`);
                
                // 复用按钮
                const reuseBtn = document.createElement('button');
                reuseBtn.className = 'reuse-btn';
                reuseBtn.textContent = '🔄 复用图片';
                reuseBtn.onclick = () => reuseImage(imageDataUrl);
                
                buttonContainer.appendChild(reuseBtn);
                buttonContainer.appendChild(downloadBtn);
                
                imageContainer.appendChild(img);
                imageContainer.appendChild(buttonContainer);
                imageGrid.appendChild(imageContainer);
                
                // 从文本内容中移除图片标记
                processedContent = processedContent.replace(match[0], '');
            }
            
            // 处理直接的 base64 数据
            if (!hasImages) {
                let base64Match;
                while ((base64Match = base64Regex.exec(content)) !== null) {
                    hasImages = true;
                    const imageDataUrl = base64Match[1];
                    
                    // 创建图片容器
                    const imageContainer = document.createElement('div');
                    imageContainer.className = 'result-image-container';
                    
                    // 创建图片元素
                    const img = document.createElement('img');
                    img.src = imageDataUrl;
                    img.className = 'result-image';
                    img.style.cssText = `
                        max-width: 100%;
                        height: auto;
                        border-radius: 8px;
                        box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
                        margin-bottom: 10px;
                    `;
                    
                    // 创建按钮容器
                    const buttonContainer = document.createElement('div');
                    buttonContainer.className = 'result-image-buttons';
                    
                    // 下载按钮
                    const downloadBtn = document.createElement('button');
                    downloadBtn.className = 'download-btn';
                    downloadBtn.textContent = '💾 下载图片';
                    downloadBtn.onclick = () => downloadImage(imageDataUrl, `generated-image-${Date.now()}.png`);
                    
                    // 复用按钮
                    const reuseBtn = document.createElement('button');
                    reuseBtn.className = 'reuse-btn';
                    reuseBtn.textContent = '🔄 复用图片';
                    reuseBtn.onclick = () => reuseImage(imageDataUrl);
                    
                    buttonContainer.appendChild(reuseBtn);
                    buttonContainer.appendChild(downloadBtn);
                    
                    imageContainer.appendChild(img);
                    imageContainer.appendChild(buttonContainer);
                    imageGrid.appendChild(imageContainer);
                    
                    // 从文本内容中移除 base64 数据
                    processedContent = processedContent.replace(base64Match[0], '');
                }
            }
            
            // 如果有剩余的文本内容，显示它
            if (processedContent.trim()) {
                const textContainer = document.createElement('div');
                textContainer.style.cssText = `
                    background: white;
                    padding: 20px;
                    border-radius: 8px;
                    margin-bottom: 15px;
                    border: 1px solid #e5e7eb;
                    white-space: pre-wrap;
                    line-height: 1.6;
                    font-size: 14px;
                    color: #374151;
                `;
                textContainer.textContent = processedContent;
                imageGrid.appendChild(textContainer);
            }
            
            resultDiv.style.display = 'block';
            clearBtn.style.display = 'inline-block';
            
            // 滚动到结果区域
            resultDiv.scrollIntoView({ behavior: 'smooth' });
        }

        function showLoading(message = '正在处理中，请稍候...') {
            const loadingDiv = document.getElementById('loading');
            const loadingText = loadingDiv.querySelector('p');
            loadingText.textContent = message;
            loadingDiv.style.display = 'block';
            
            // 禁用提交按钮
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = true;
        }

        function hideLoading() {
            document.getElementById('loading').style.display = 'none';
            
            // 启用提交按钮
            const submitBtn = document.getElementById('submitBtn');
            submitBtn.disabled = false;
        }

        function showError(message) {
            const errorDiv = document.getElementById('error');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
        }

        function hideError() {
            document.getElementById('error').style.display = 'none';
        }

        function showFloatingMessage(message) {
            const messageDiv = document.createElement('div');
            messageDiv.className = 'floating-success';
            messageDiv.textContent = message;
            document.body.appendChild(messageDiv);
            
            setTimeout(() => {
                if (messageDiv.parentNode) {
                    messageDiv.parentNode.removeChild(messageDiv);
                }
            }, 2000);
        }
        
        function downloadImage(dataUrl, filename) {
            const link = document.createElement('a');
            link.href = dataUrl;
            link.download = filename;
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            showFloatingMessage('图片下载已开始');
        }
        
        function reuseImage(dataUrl) {
            // 将图片添加到当前图片列表中
            const imageObj = {
                data: dataUrl,
                name: `generated-${Date.now()}.png`,
                type: 'generated'
            };
            
            currentImages.push(imageObj);
            updateImageDisplay();
            showFloatingMessage('图片已添加到输入列表');
        }
    </script>
</body>

</html>